<template>
	<view class="page__content">
		<template v-if="props.showNavbar">
			<up-navbar :fixed="false" :autoBack="false" :safeAreaInsetTop="true">
				<template #left>
					<text class="navbar-title">汇创云 QMS</text>
				</template>
			</up-navbar>
		</template>

		<view class="page__content__main">
			<!-- 我的设备 -->
			<view class="device-card">
				<view class="device-card__header">
					<view class="device-card__header-left">
						<text class="device-card__title">我的设备</text>
						<text class="device-card__count">（{{ getConnectedDevices.length }}）</text>
					</view>
				</view>

				<view class="device-card__body">
					<!-- 无设备 -->
					<view v-if="!getConnectedDevices.length" class="device-empty">
						<text class="device-empty__text">当前暂无设备连接记录，请前往连接！</text>
					</view>

					<!-- 有设备 -->
					<view v-else class="device-list">

						<uni-row :gutter="20" style="width: 100%;">
							<uni-col v-for="item in getConnectedDevices" :key="item.deviceId" :span="ColSpan"
								:md="{ span: 6 }" :lg="{ span: 4 }">
								<view class="device-item" @click="handlerClickToLink(item)">

									<view class="device-item__status"
										:class="{'device-item__status--active': item.connected}">
									</view>

									<view class="device-item__top">
										<image :src="item.config.FilePath" class="device-item__icon" />
										<view class="device-item__info">
											<text class="device-item__name">{{ item.aliasName || item.name }}</text>
											<text class="device-item__measure">{{ item.config.MeasureName }}</text>
										</view>
									</view>

									<view class="device-item__bottom">
										<text class="device-item__spec">{{ item.config.MeasureSpec }}</text>
									</view>

								</view>
							</uni-col>
						</uni-row>



						<!-- <view v-for="item in getConnectedDevices" :key="item.deviceId" class="device-item"
							@click="handlerClickToLink(item)">
							<view class="device-item__status" :class="{'device-item__status--active': item.connected}">
							</view>

							<view class="device-item__top">
								<image :src="item.config.FilePath" class="device-item__icon" />
								<view class="device-item__info">
									<text class="device-item__name">{{ item.aliasName || item.name }}</text>
									<text class="device-item__measure">{{ item.config.MeasureName }}</text>
								</view>
							</view>

							<view class="device-item__bottom">
								<text class="device-item__spec">{{ item.config.MeasureSpec }}</text>
							</view>
						</view> -->
					</view>
				</view>
			</view>

			<!-- 设备类型 -->
			<view class="device-type">
				<view class="device-type__header">
					<text class="device-type__title">选择设备类型</text>
				</view>

				<view class="device-type__list">
					<view v-for="(item, index) in DeviceList" :key="index" class="device-type__group">
						<text v-if="item.children.length"
							class="device-type__group-title">{{ item.ApplianceTypeName }}:</text>

						<uni-row class="device-type__row" :gutter="20">
							<uni-col v-for="(ReItem, index) in item.children" :key="index" :span="ColSpan"
								:md="{ span: 6 }" :lg="{ span: 4 }">
								<view class="device-type__card" @click="ChoiceDevice(ReItem)">
									<u--image :showLoading="true" :src="judgeImg(ReItem.FilePath)" mode="widthFix"
										width="30px" height="30px" />
									<text class="device-type__name">{{ ReItem.DeviceName }}</text>
								</view>
							</uni-col>
						</uni-row>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>


<script setup lang="ts" name="page-device-control">
	import { reactive, computed, onMounted, ref, nextTick, getCurrentInstance, watch } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { useMainStore, useQmsStore, usePermissionStore, useUserStore, useBluetoothStore } from '@/store';
	const qmsStore = useQmsStore();
	const mainStore = useMainStore();
	const permissionStore = usePermissionStore();
	const userStore = useUserStore();
	const bluetoothStore = useBluetoothStore();
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();



	const props = defineProps({
		showNavbar: {
			type: Boolean,
			default: true
		}
	});


	// 已配对设备数据
	let getConnectedDevices = computed(() => {
		const data = bluetoothStore.getConnectedDevices;

		return Object.values(data).sort((a, b) => {
			if (a.connected && !b.connected) return -1;
			if (!a.connected && b.connected) return 1;
			return 0;
		});
	});



	// const initData = uni.$utils.$bluetooth.openBluetooth()


	// 设备分类块
	let ColSpan = ref(12);
	let DeviceList = ref<any>([]);

	const systemInfo = mainStore.systemConfig.sysDeviceInfo;
	if (systemInfo.windowWidth <= 500) { // 一行两个
		ColSpan.value = 12;
	} else if (systemInfo.windowWidth > 500 && systemInfo.windowWidth < 1000) { // 一行三个
		ColSpan.value = 8;
	};
	const judgeImg = (data : any) => {
		if (uni.$utils.isEmpty(data)) {
			return ""
		} else if (!/^http[s]?:\/\/.*/.test(data)) {
			mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + data;
		} else {
			return data
		}
	}
	const ChoiceDevice = (data : any) => {
		// 在文件顶部或配置文件中定义
		const DEVICE_NAMES = new Set([
			'游标卡尺', '千分尺', '高度尺', '千分表',
			'深度尺', '光谱仪', '三坐标', '串口',
			'影像测量仪', '百分表'
		]);

		// 使用
		if (DEVICE_NAMES.has(data.DeviceName)) {
			uni.navigateTo({
				url: "/st_qms/page_device/page_device_list" + `?Name=${data.DeviceName}&ClassifyID=${data.MeasureTypeID}`
			});
		} else {
			uni.showToast({
				title: '暂未授权该设备',
				icon: "none",
			});
		}

	}
	// 获取设备类型数据
	const GetDeviceList = () => {
		request({
			config: {
			},
			url: 'APP_JLSBFLLIST1',
			method: 'POST',
			data: {},
			success: async (ret : any) => {
				if (ret.status == 200) {
					let _TreeData = tranList(ret.data.ds, 0, 'UpID', 'MeasureTypeID')

					_TreeData[0].children.forEach((item : any) => {
						let ChildrenList = []
						ret.data.ds1.forEach((ReItem : any) => {
							if (ReItem.UpID == item.MeasureTypeID) {
								ChildrenList.push(ReItem)
							}
						})
						item.children = ChildrenList
					})

					DeviceList.value = _TreeData[0].children;
				}
			}
		})
	};
	function tranList(list : any, rootVal : any, PID : any, ID : any) {
		let childItem = [];
		for (let i = 0; i < list.length; i++) {
			let childObj = {} as any;
			if (list[i][PID] == rootVal) {
				childObj = list[i];
				childObj.children = tranList(list, list[i][ID], PID, ID);
				childItem.push(childObj);
			}
		}
		return childItem;
	}

	// 点击已配对设备
	const handlerClickToLink = (data : any) => {
		uni.navigateTo({
			url: "/st_qms/page_device/page_device_link" + "?deviceId=" + data.deviceId
		})
	};

	onLoad(() => {
		GetDeviceList();
	})
</script>

<style lang="scss" scoped>
	.page__content {
		height: 100%;
		background-image: linear-gradient(to bottom,
				rgba(81, 208, 208, 1),
				rgba(81, 208, 208, 1),
				rgba(81, 208, 208, 0.7) 30%,
				rgba(255, 255, 255, 0));

		.navbar-title {
			font-size: 26rpx;
			color: #fff;
			font-weight: 600;
		}

		&__main {
			padding: 15rpx;
		}

		.device-card {
			background: #fff;
			border-radius: 40rpx;
			margin-top: 20rpx;
			padding: 15rpx;
			font-size: 24rpx;

			&__header {
				display: flex;
				justify-content: space-between;
				align-items: center;
			}

			&__title {
				font-weight: 600;
				margin-left: 8rpx;
			}

			&__count {
				color: #666;
			}

			&__body {
				margin-top: 30rpx;
			}
		}

		.device-empty {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 280rpx;
			width: 100%;

			&__text {
				color: #999;
				font-size: 24rpx;
				font-weight: 600;
			}
		}

		.device-list {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx 15rpx;
			padding: 15rpx 10rpx;
			background-color: #f9f9f9;
			border-radius: 20rpx;
		}

		.device-item {
			position: relative;
			display: flex;
			flex-direction: column;
			background: #fff;
			border-radius: 20rpx;
			// width: 200rpx;
			width: 100%;
			height: 150rpx;
			padding: 10rpx;

			&__status {
				position: absolute;
				top: 8rpx;
				right: 10rpx;
				width: 12rpx;
				height: 12rpx;
				border-radius: 50%;
				background-color: #e3e7e7;

				&--active {
					background-color: #05bc4f;
				}
			}

			&__top {
				display: flex;
				align-items: center;
			}

			&__icon {
				width: 40px;
				height: 40px;
				border-radius: 15px;
				background: #f9f9f9;
			}

			&__info {
				margin-left: 10rpx;
				flex: 1;
				display: flex;
				flex-direction: column;
			}

			&__name {
				font-size: 14px;
				font-weight: 600;
			}

			&__measure {
				font-size: 12px;
				color: #999;
			}

			&__bottom {
				font-size: 12px;
				color: #999;
				margin-top: auto;
			}
		}

		.device-type {
			background: #fff;
			border-radius: 20rpx;
			margin-top: 15rpx;
			padding: 20rpx;

			&__title {
				font-size: 24rpx;
				font-weight: 600;
			}

			&__group {
				padding: 15rpx 0;

				&-title {
					font-size: 24rpx;
					color: #afadc4;
				}
			}

			&__card {
				display: flex;
				align-items: center;
				height: 80px;
				padding: 10rpx;
				border-radius: 20rpx;
				background: #f5f5f5;
				color: #7e7e81;
				transition: all 0.2s ease;
				margin-top: 20rpx;

				&:active {
					background: #e8e8e8;
				}
			}

			&__name {
				font-size: 20rpx;
				margin-left: 15rpx;
			}
		}
	}
</style>